<!DOCTYPE html>






<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">







  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">


















  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">



















































<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="Android UI 专题,">










<meta name="description" content="AsyncTask详解AsyncTask中的参数AsyncTask是一个抽象类,如果我们想使用它就要自定义一个子类去继承它。继成时我们可以为AsyncTask制定三个泛型参数:  Params:调用AsyncTask的excute方法时传入的参数类型，如果该方法传入了多个不同类型的参数，那么就定义为Object。 Progress:执行AsyncTask时如果需要在前台显示进度条,使用该类型作为进">
<meta name="keywords" content="Android UI 专题">
<meta property="og:type" content="article">
<meta property="og:title" content="AsyncTask详解">
<meta property="og:url" content="https://zachaxy.github.io/2017/10/17/AsyncTask详解/index.html">
<meta property="og:site_name" content="zachaxy">
<meta property="og:description" content="AsyncTask详解AsyncTask中的参数AsyncTask是一个抽象类,如果我们想使用它就要自定义一个子类去继承它。继成时我们可以为AsyncTask制定三个泛型参数:  Params:调用AsyncTask的excute方法时传入的参数类型，如果该方法传入了多个不同类型的参数，那么就定义为Object。 Progress:执行AsyncTask时如果需要在前台显示进度条,使用该类型作为进">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-09-01T11:13:24.294Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="AsyncTask详解">
<meta name="twitter:description" content="AsyncTask详解AsyncTask中的参数AsyncTask是一个抽象类,如果我们想使用它就要自定义一个子类去继承它。继成时我们可以为AsyncTask制定三个泛型参数:  Params:调用AsyncTask的excute方法时传入的参数类型，如果该方法传入了多个不同类型的参数，那么就定义为Object。 Progress:执行AsyncTask时如果需要在前台显示进度条,使用该类型作为进">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"right","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zachaxy.github.io/2017/10/17/AsyncTask详解/">





  <title>AsyncTask详解 | zachaxy</title>









</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">






  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">


    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zachaxy</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>

        <h1 class="site-subtitle" itemprop="description">纵情向前！</h1>

  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">



    <ul id="menu" class="menu">


        <li class="menu-item menu-item-home">
          <a href="/" rel="section">

              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>

            首页
          </a>
        </li>


        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">

              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>

            标签
          </a>
        </li>


        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">

              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>

            归档
          </a>
        </li>


        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">

              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>

            关于
          </a>
        </li>



        <li class="menu-item menu-item-search">

            <a href="javascript:;" class="popup-trigger">


              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>

            搜索
          </a>
        </li>

    </ul>



    <div class="site-search">

  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>

</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">


  <div id="posts" class="posts-expand">








  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/10/17/AsyncTask详解/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">AsyncTask详解</h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-10-17T19:49:18+08:00">
                2017-10-17
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  3,627
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">





        <h2 id="AsyncTask详解"><a href="#AsyncTask详解" class="headerlink" title="AsyncTask详解"></a>AsyncTask详解</h2><h3 id="AsyncTask中的参数"><a href="#AsyncTask中的参数" class="headerlink" title="AsyncTask中的参数"></a>AsyncTask中的参数</h3><p>AsyncTask是一个抽象类,如果我们想使用它就要自定义一个子类去继承它。继成时我们可以为<br>AsyncTask制定三个泛型参数:</p>
<ul>
<li>Params:调用AsyncTask的excute方法时传入的参数类型，如果该方法传入了多个不同类型的参数，那么就定义为Object。</li>
<li>Progress:执行AsyncTask时如果需要在前台显示进度条,使用该类型作为进度的单位</li>
<li>Result:当AsyncTask结束后,如果需要对结果进行返回,该类型作为返回值的类型</li>
</ul>
<p>如果某一个类型不需要传递具体的参数,那么对应的泛型参数用<code>Void</code>代替</p>
<h3 id="AsyncTask中一些重要的方法"><a href="#AsyncTask中一些重要的方法" class="headerlink" title="AsyncTask中一些重要的方法"></a>AsyncTask中一些重要的方法</h3><ul>
<li>void onPreExecute():在主线程执行,用于进行一些界面上的初始化操作,eg:显示一个进度条对话框等</li>
</ul>
<ul>
<li>Result doInBackground(Params … params):在子线程中执行,用于执行耗时任务,相当于Thread中的run()方法</li>
<li>void onProgressUpdate(Progress… values):在主线程中执行,前提是在<code>doInBackground</code>方法中执行了publishProgress(Progress… values),由该方法自动调用<code>onProgressUpdate</code>,可以界面上实时显示进度</li>
<li>void onPostExecute(Result res),在子线程中执行,<code>doInBackground</code>方法执行结束后,将返回值传给该方法,负责任务结束后的工作</li>
<li>void publishProgress(Progress… values),一般在<code>doInBackground</code>方法中调用(非必须),将当前进度传递出来,一旦执行了该方法,那么将自动回调onProgressUpdate方法,并将当前进度作为参数传递给它.</li>
<li>void onCancelled(boolean cancel),在主线程中执行,如果被调用,那么<code>onPostExecute</code>方法不会被执行,详见源码解析.</li>
</ul>
<h3 id="AsyncTask的基本使用"><a href="#AsyncTask的基本使用" class="headerlink" title="AsyncTask的基本使用"></a>AsyncTask的基本使用</h3><p>一个简单的下载的例子</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AsyncTaskTest</span> <span class="keyword">extends</span> <span class="title">Activity</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">	<span class="keyword">private</span> TextView show;</span><br><span class="line"></span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onCreate</span><span class="params">(Bundle savedInstanceState)</span></span></span><br><span class="line"><span class="function">	</span>&#123;</span><br><span class="line">		<span class="keyword">super</span>.onCreate(savedInstanceState);</span><br><span class="line">		setContentView(R.layout.main);</span><br><span class="line">		show = (TextView) findViewById(R.id.show);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 此方法为界面的按钮提供事件响应方法,</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">download</span><span class="params">(View source)</span> <span class="keyword">throws</span> MalformedURLException</span></span><br><span class="line"><span class="function">	</span>&#123;</span><br><span class="line">		DownTask task = <span class="keyword">new</span> DownTask(<span class="keyword">this</span>);</span><br><span class="line">		task.execute(<span class="keyword">new</span> URL(<span class="string">"http://www.crazyit.org/ethos.php"</span>));</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="class"><span class="keyword">class</span> <span class="title">DownTask</span> <span class="keyword">extends</span> <span class="title">AsyncTask</span>&lt;<span class="title">URL</span>, <span class="title">Integer</span>, <span class="title">String</span>&gt;</span></span><br><span class="line"><span class="class">	</span>&#123;</span><br><span class="line">		<span class="comment">// 可变长的输入参数，与AsyncTask.exucute()对应</span></span><br><span class="line">		ProgressDialog pdialog;</span><br><span class="line">		<span class="comment">// 定义记录已经读取行的数量</span></span><br><span class="line">		<span class="keyword">int</span> hasRead = <span class="number">0</span>;</span><br><span class="line">		Context mContext;</span><br><span class="line"></span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="title">DownTask</span><span class="params">(Context ctx)</span></span></span><br><span class="line"><span class="function">		</span>&#123;</span><br><span class="line">			mContext = ctx;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="meta">@Override</span></span><br><span class="line">		<span class="function"><span class="keyword">protected</span> String <span class="title">doInBackground</span><span class="params">(URL... params)</span></span></span><br><span class="line"><span class="function">		</span>&#123;</span><br><span class="line">			StringBuilder sb = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">			<span class="keyword">try</span></span><br><span class="line">			&#123;</span><br><span class="line">				URLConnection conn = params[<span class="number">0</span>].openConnection();</span><br><span class="line">				<span class="comment">// 打开conn连接对应的输入流，并将它包装成BufferedReader</span></span><br><span class="line">				BufferedReader br = <span class="keyword">new</span> BufferedReader(</span><br><span class="line">					<span class="keyword">new</span> InputStreamReader(conn.getInputStream()</span><br><span class="line">					, <span class="string">"utf-8"</span>));</span><br><span class="line">				String line = <span class="keyword">null</span>;</span><br><span class="line">				<span class="keyword">while</span> ((line = br.readLine()) != <span class="keyword">null</span>)</span><br><span class="line">				&#123;</span><br><span class="line">					sb.append(line + <span class="string">"\n"</span>);</span><br><span class="line">					hasRead++;</span><br><span class="line">					publishProgress(hasRead);</span><br><span class="line">				&#125;</span><br><span class="line">				<span class="keyword">return</span> sb.toString();</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">catch</span> (Exception e)</span><br><span class="line">			&#123;</span><br><span class="line">				e.printStackTrace();</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="meta">@Override</span></span><br><span class="line">		<span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onPostExecute</span><span class="params">(String result)</span></span></span><br><span class="line"><span class="function">		</span>&#123;</span><br><span class="line">			<span class="comment">// 返回HTML页面的内容</span></span><br><span class="line">			show.setText(result);</span><br><span class="line">			pdialog.dismiss();</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="meta">@Override</span></span><br><span class="line">		<span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onPreExecute</span><span class="params">()</span></span></span><br><span class="line"><span class="function">		</span>&#123;</span><br><span class="line">			pdialog = <span class="keyword">new</span> ProgressDialog(mContext);</span><br><span class="line">			<span class="comment">// 设置对话框的标题</span></span><br><span class="line">			pdialog.setTitle(<span class="string">"任务正在执行中"</span>);</span><br><span class="line">			<span class="comment">// 设置对话框 显示的内容</span></span><br><span class="line">			pdialog.setMessage(<span class="string">"任务正在执行中，敬请等待..."</span>);</span><br><span class="line">			<span class="comment">// 设置对话框不能用“取消”按钮关闭</span></span><br><span class="line">			pdialog.setCancelable(<span class="keyword">false</span>);</span><br><span class="line">			<span class="comment">// 设置该进度条的最大进度值</span></span><br><span class="line">			pdialog.setMax(<span class="number">202</span>);</span><br><span class="line">			<span class="comment">// 设置对话框的进度条风格</span></span><br><span class="line">			pdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);</span><br><span class="line">			<span class="comment">// 设置对话框的进度条是否显示进度</span></span><br><span class="line">			pdialog.setIndeterminate(<span class="keyword">false</span>);</span><br><span class="line">			pdialog.show();</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="meta">@Override</span></span><br><span class="line">		<span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onProgressUpdate</span><span class="params">(Integer... values)</span></span></span><br><span class="line"><span class="function">		</span>&#123;</span><br><span class="line">			<span class="comment">// 更新进度</span></span><br><span class="line">			show.setText(<span class="string">"已经读取了【"</span> + values[<span class="number">0</span>] + <span class="string">"】行！"</span>);</span><br><span class="line">			pdialog.setProgress(values[<span class="number">0</span>]);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>AsyncTask的启动只需要执行:task.execute(Param … params);可以想其execute()方法中传入多个Param,代表多个任务,(eg:这个例子中可以传入多个url,那么就可以进行多个的下载),可以同时进行,其内部使用了线程池原理;</p>
<h3 id="AsyncTask中的注意事项"><a href="#AsyncTask中的注意事项" class="headerlink" title="AsyncTask中的注意事项"></a>AsyncTask中的注意事项</h3><ol>
<li>AsyncTask的类必须在主线程进行加载,也就是说第一次访问AsyncTask必须在主线程,在4.1之后的版本中,被系统自动完成,在5.0的代码中,在ActivityThread.main()中,调用了AsyncTask.init()方法来实现在主线程中被加载</li>
<li>AsyncTask对象必须在主线程中创建</li>
<li>execute()方法必须在UI线程中调用</li>
<li>不要在持续中自己调用onPreExecute(),doInBackground()等方法</li>
<li>一个AsyncTask对象执行一次execute()方法,多次执行会报错;</li>
<li>AsyncTask在不同版本上的表现是不一样的,eg:1.6版本之前,串行执行任务;1.6时,采用线程池并行处理任务;3.0开始又采用一个线程来串行执行任务;</li>
</ol>
<h3 id="AsyncTask源码解析"><a href="#AsyncTask源码解析" class="headerlink" title="AsyncTask源码解析"></a>AsyncTask源码解析</h3><p>这里分析的版本是Andoid4.0/4.2,不同的版本可能稍有不同;</p>
<p>首先从AsyncTask的execute()方法分析</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> AsyncTask&lt;Params, Progress, Result&gt; <span class="title">execute</span><span class="params">(Params... params)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> executeOnExecutor(sDefaultExecutor, params);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 额,只有一句话,具体实现在下面;</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> AsyncTask&lt;Params, Progress, Result&gt; <span class="title">executeOnExecutor</span><span class="params">(Executor exec,Params... params)</span> </span>&#123;  </span><br><span class="line">    <span class="keyword">if</span> (mStatus != Status.PENDING) &#123;  </span><br><span class="line">        <span class="keyword">switch</span> (mStatus) &#123;  </span><br><span class="line">            <span class="keyword">case</span> RUNNING:  </span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">"Cannot execute task:"</span>  </span><br><span class="line">                        + <span class="string">" the task is already running."</span>);  </span><br><span class="line">            <span class="keyword">case</span> FINISHED:  </span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">"Cannot execute task:"</span>  </span><br><span class="line">                        + <span class="string">" the task has already been executed "</span>  </span><br><span class="line">                        + <span class="string">"(a task can be executed only once)"</span>);  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">    mStatus = Status.RUNNING;  </span><br><span class="line">    onPreExecute();  </span><br><span class="line">    mWorker.mParams = params;  </span><br><span class="line">    exec.execute(mFuture);  </span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里关注的点是:</p>
<ol>
<li>最后将<code>mStatus</code>设置为<code>RUNNING</code>,由此也可以得出AsyncTask只能执行一次,否则其execute()方法一进去判断状态,如果已经是<code>RUNNING</code>,直接报错</li>
<li>执行了<code>onPreExecute()</code>方法,因此证明了onPreExecute()方法会第一个得到执行,当前依然在UI线程，所以我们可以在其中做一些准备工作。</li>
<li>调用了Executor的execute()方法，并将前面初始化的mFuture对象传了进去</li>
<li>mWorker.mParams = params,将我们传入的参数赋值给了mWorker.mParams</li>
<li>exec.execute(mFuture)</li>
</ol>
<p>相信大家对与<code>mWorker</code>和<code>mFuture</code>感到困惑,我们找到这两个类</p>
<p>其在<code>AsyncTask</code>中的定义<code>private final WorkerRunnable&lt;Params, Result&gt; mWorker;</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">WorkerRunnable</span>&lt;<span class="title">Params</span>, <span class="title">Result</span>&gt; <span class="keyword">implements</span> <span class="title">Callable</span>&lt;<span class="title">Result</span>&gt; </span>&#123;  </span><br><span class="line">        Params[] mParams;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以看到是Callable的子类，且包含一个<code>mParams</code>用于保存我们传入的参数，下面看初始化mWorker的代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">AsyncTask</span><span class="params">()</span> </span>&#123;  </span><br><span class="line">        mWorker = <span class="keyword">new</span> WorkerRunnable&lt;Params, Result&gt;() &#123;  </span><br><span class="line">          	<span class="comment">//重写了call方法,只要mWorker一启动,就执行call方法,在call方法中先执行doInBackground方法</span></span><br><span class="line">          	<span class="comment">//然后将其结果作为postResult的参数传入postResult()中,作为callable接口的返回值,此时依然在子线程中</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> Result <span class="title">call</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;  </span><br><span class="line">                mTaskInvoked.set(<span class="keyword">true</span>);  </span><br><span class="line">  				<span class="comment">//设置线程优先级:后台线程;</span></span><br><span class="line">                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);  </span><br><span class="line">                <span class="comment">//noinspection unchecked </span></span><br><span class="line">                <span class="keyword">return</span> postResult(doInBackground(mParams));  </span><br><span class="line">            &#125;  </span><br><span class="line">        &#125;;  </span><br><span class="line"><span class="comment">//….  </span></span><br><span class="line">          </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以看到mWorker在构造方法中完成了初始化，并且因为是一个抽象类，在这里new了一个实现类，实现了call方法，call方法中设置mTaskInvoked=true，且最终调用doInBackground(mParams)方法，并返回Result值作为参数给postResult方法.这基本上就将 中几个重要函数的执行流程描述清楚了.</p>
<p>这里也出现了最重要的方法<code>doInBackground()</code>,我们知道<code>doInBackground()</code>的返回值是是作为参数传给<code>onPostExecute(Result res)</code>,为什么是作为参数传给了<code>postResult</code>呢?</p>
<p>其实可以想到:<code>doInBackground()</code>方法的执行是在子线程的,而<code>onPostExecute(Result res)</code>方法是在主线程的,这里直接传递是不可能的,需要一个中间的桥梁来实现线程的切换,这个桥梁就是<code>postResult();</code></p>
<p>接着往下看,<code>postResult</code>中具体做了什么</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> Result <span class="title">postResult</span><span class="params">(Result result)</span> </span>&#123;  </span><br><span class="line">        <span class="meta">@SuppressWarnings</span>(<span class="string">"unchecked"</span>)  </span><br><span class="line">        Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,  </span><br><span class="line">                <span class="keyword">new</span> AsyncTaskResult&lt;Result&gt;(<span class="keyword">this</span>, result));  <span class="comment">//第一个参数是当前的task,这个方法是task中的方法</span></span><br><span class="line">        message.sendToTarget();  </span><br><span class="line">        <span class="keyword">return</span> result;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>果然,这里用到了<code>handler</code>的消息传递机制,是在子线程中将结果传递出去,结合之前所说的AsyncTask类的加载必须在主线程,那么我们还可以料想到这个主线程中的AsyncTask在初始化时也创建了一个handler,并且重写了handleMessage()方法,在该方法中根据Message.What,来将返回的消息结果传给onPostExecute(Result res),这样整个消息就从子线程传递到主线程了.</p>
<p>是不是上面预想的那样,接着看代码,先看一下<code>AsyncTaskResult</code>这个类里有什么,这是一个静态内部类,封装了当前的AsyncTask对象和要返回的结果集,其实这个结果集并没有什么用,因为最终取的还是第一个值 data[0].</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">AsyncTaskResult</span>&lt;<span class="title">Data</span>&gt; </span>&#123;  </span><br><span class="line">       <span class="keyword">final</span> AsyncTask mTask;  </span><br><span class="line">       <span class="keyword">final</span> Data[] mData;  </span><br><span class="line">  </span><br><span class="line">       AsyncTaskResult(AsyncTask task, Data... data) &#123;  </span><br><span class="line">           mTask = task;  </span><br><span class="line">           mData = data;  </span><br><span class="line">       &#125;  </span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<p>接下来看一下AsyncTask中的handler对象在哪里?</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> InternalHandler sHandler = <span class="keyword">new</span> InternalHandler(); <span class="comment">//AsyncTask中的成员变量</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//接下来看一下这个handler是专门处理详细的, 在handleMessage(msg)方法中已经说得很清楚了.</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">InternalHandler</span> <span class="keyword">extends</span> <span class="title">Handler</span> </span>&#123;  </span><br><span class="line">        <span class="meta">@SuppressWarnings</span>(&#123;<span class="string">"unchecked"</span>, <span class="string">"RawUseOfParameterizedType"</span>&#125;)  </span><br><span class="line">        <span class="meta">@Override</span>  </span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">handleMessage</span><span class="params">(Message msg)</span> </span>&#123;  </span><br><span class="line">            AsyncTaskResult result = (AsyncTaskResult) msg.obj;  </span><br><span class="line">            <span class="keyword">switch</span> (msg.what) &#123;  </span><br><span class="line">                <span class="keyword">case</span> MESSAGE_POST_RESULT:  </span><br><span class="line">                    <span class="comment">// There is only one result  </span></span><br><span class="line">                    result.mTask.finish(result.mData[<span class="number">0</span>]);  </span><br><span class="line">                    <span class="keyword">break</span>;  </span><br><span class="line">                <span class="keyword">case</span> MESSAGE_POST_PROGRESS:  </span><br><span class="line">                    result.mTask.onProgressUpdate(result.mData);  </span><br><span class="line">                    <span class="keyword">break</span>;  </span><br><span class="line">            &#125;  </span><br><span class="line">        &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们先看正常发出的标签 msg.what是<code>MESSAGE_POST_RESULT</code>,这里调用了<code>result.mTask.finish(result.mData[0]);</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">finish</span><span class="params">(Result result)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (isCancelled()) &#123;</span><br><span class="line">            onCancelled(result);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            onPostExecute(result);</span><br><span class="line">        &#125;</span><br><span class="line">        mStatus = Status.FINISHED;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>看到这里进行了判断,如果该任务被取消了,那么走<code>onCancelled(result)</code>的分支,否则,执行<code>onPostExecute(result)</code>,最后将状态设置为<code>最后将状态置为FINISHED</code>,整个任务就结束了.</p>
<p>mWoker看完了，应该到我们的mFuture了，我们在使用Future的时候,是将其作为参数传入Thread中的,依然实在构造方法中完成mFuture的初始化，将mWorker作为参数，复写了其done方法。done()方法是在其成员变量Callable中的call()方法执行结束之后才执行的回调,此时调用其get()方法不会阻塞主线程,</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">AsyncTask</span><span class="params">()</span> </span>&#123;  </span><br><span class="line">    ...  </span><br><span class="line">        mFuture = <span class="keyword">new</span> FutureTask&lt;Result&gt;(mWorker) &#123;  </span><br><span class="line">            <span class="meta">@Override</span>  </span><br><span class="line">            <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">done</span><span class="params">()</span> </span>&#123;  </span><br><span class="line">                <span class="keyword">try</span> &#123;  </span><br><span class="line">                    postResultIfNotInvoked(get());  </span><br><span class="line">                &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;  </span><br><span class="line">                    android.util.Log.w(LOG_TAG, e);  </span><br><span class="line">                &#125; <span class="keyword">catch</span> (ExecutionException e) &#123;  </span><br><span class="line">                    <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"An error occured while executing doInBackground()"</span>,  </span><br><span class="line">                            e.getCause());  </span><br><span class="line">                &#125; <span class="keyword">catch</span> (CancellationException e) &#123;  </span><br><span class="line">                    postResultIfNotInvoked(<span class="keyword">null</span>);  </span><br><span class="line">                &#125;  </span><br><span class="line">            &#125;  </span><br><span class="line">        &#125;;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里在任务执行结束后调用了<code>postResultIfNotInvoked(get())</code>,看一下这个方法是如何实现的</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">postResultIfNotInvoked</span><span class="params">(Result result)</span> </span>&#123;  </span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">boolean</span> wasTaskInvoked = mTaskInvoked.get();  </span><br><span class="line">    <span class="keyword">if</span> (!wasTaskInvoked) &#123;  </span><br><span class="line">        postResult(result);  </span><br><span class="line">   &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果<code>mTaskInvoked</code>不为<code>true</code>，则执行<code>postResult</code>；但是在<code>mWorker</code>初始化时就已经将<code>mTaskInvoked</code>为<code>true</code>，所以一般这个<code>postResult()</code>执行不到。</p>
<p>小总结一下:这里是介绍了两个变量的初始化:分别是<code>mWorker</code> 以及<code>mFuture</code>,这里<code>mWorker</code> 其实是一个<code>Callable</code>,<code>mFuture</code>其实是一个<code>FutureTask</code></p>
<p>具体使用还请参考《疯狂Java讲义》中的关于Callable和Future的使用吧</p>
<p>好了，到了这里，已经介绍完了execute方法中出现了mWorker和mFurture，不过这里一直是初始化这两个对象的代码，并没有真正的执行。下面我们看真正调用执行的地方。</p>
<p>excute()方法</p>
<p>还记得上面的<code>execute</code>中：exec.execute(mFuture),其中<code>exec</code>为<code>executeOnExecutor(sDefaultExecutor, params)</code>中的<code>sDefaultExecutor</code><br>下面看这个<code>sDefaultExecutor</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">volatile</span> Executor sDefaultExecutor = SERIAL_EXECUTOR;  </span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> Executor SERIAL_EXECUTOR = <span class="keyword">new</span> SerialExecutor();  </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">SerialExecutor</span> <span class="keyword">implements</span> <span class="title">Executor</span> </span>&#123;  </span><br><span class="line">  <span class="comment">//维持一个队列,队列里面盛放的是 Runnable,而FutureTask 正好实现了 Runnable 接口;</span></span><br><span class="line">   <span class="keyword">final</span> ArrayDeque&lt;Runnable&gt; mTasks = <span class="keyword">new</span> ArrayDeque&lt;Runnable&gt;();  </span><br><span class="line">  </span><br><span class="line">   Runnable mActive;  </span><br><span class="line">  </span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">execute</span><span class="params">(<span class="keyword">final</span> Runnable r)</span> </span>&#123;  </span><br><span class="line">     <span class="comment">//差点又被误导了,这里是指创建了一个Runnable,其中的run方法是在线程池被调用的时候执行的,而不是现在;</span></span><br><span class="line">     <span class="comment">//这里只是往上面的队列mTask中提交一个runnable对象,这个runnable对象时什么呢,就是我们所提供的mFuture对象;</span></span><br><span class="line">            mTasks.offer(<span class="keyword">new</span> Runnable() &#123;  </span><br><span class="line">              	<span class="meta">@override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;  </span><br><span class="line">                    <span class="keyword">try</span> &#123;  </span><br><span class="line">                        r.run();  <span class="comment">//这个步骤本身就是一个阻塞的,会经过一段时间,执行过程中可能有新的任务添加进来</span></span><br><span class="line">                    &#125; <span class="keyword">finally</span> &#123;  </span><br><span class="line">                        scheduleNext();  </span><br><span class="line">                    &#125;  </span><br><span class="line">                &#125;  </span><br><span class="line">            &#125;);  </span><br><span class="line">            <span class="keyword">if</span> (mActive == <span class="keyword">null</span>) &#123;  <span class="comment">//当前没有要执行的任务,那么就取出队列的第一个任务开始执行;</span></span><br><span class="line">                scheduleNext();  </span><br><span class="line">            &#125;  </span><br><span class="line">        &#125;  </span><br><span class="line">   </span><br><span class="line">  <span class="function"><span class="keyword">protected</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">scheduleNext</span><span class="params">()</span> </span>&#123;  </span><br><span class="line">            <span class="keyword">if</span> ((mActive = mTasks.poll()) != <span class="keyword">null</span>) &#123;  </span><br><span class="line">                THREAD_POOL_EXECUTOR.execute(mActive);  <span class="comment">//此时才会执行其r.run()方法,真正执行的线程池是这个,而上一个SERIAL_EXECUTOR的线程池只负责线程串行的调度;</span></span><br><span class="line">            &#125;  </span><br><span class="line">        &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以看到sDefaultExecutor其实为SerialExecutor的一个实例,(SerialExecutor实现了Executor接口,该接口中只有一个void execute(Runnable r)方法)其内部维持一个任务队列;直接看其execute（Runnable runnable）方法，将runnable放入mTasks队尾,但是这里提供的Runnable并不是AsyncTask在构造方法中创建的FutureTask(虽然FutureTask也是一个Runnable),而是自己new了一个Runnable对象,在其run的内部手动调用了FutureTask.run(),最后执行scheduleNext()方法.</p>
<p>这个时候就要说一下其实AsyncTask其实是串行执行任务的,我们向<code>ArrayDeque&lt;Runnable&gt; mTasks</code>中添加一个任务(注意这里只是添加并不是执行…),添加完后都会判断mActivie是不是为null,如果此时没有任务在执行,那么就会调用scheduleNext()方法,但是此时不为null的话,就什么也不做,仅仅是添加任务,而当scheduleNext()中执行完一个任务后,其finally中会再次调用scheduleNext()方法,执行下一个任务,这就做到了串行…</p>
<h2 id="问题-既然AsyncTask只能execute一次-要线程池干什么"><a href="#问题-既然AsyncTask只能execute一次-要线程池干什么" class="headerlink" title="问题:既然AsyncTask只能execute一次,要线程池干什么?"></a>问题:既然AsyncTask只能execute一次,要线程池干什么?</h2><p>两个原因:</p>
<p>(一)同一个AsyncTask只能execute()一次,如果代码是</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> AsyncTask().execute();</span><br><span class="line"><span class="keyword">new</span> AsyncTask().execute();</span><br><span class="line"><span class="keyword">new</span> AsyncTask().execute();</span><br><span class="line"><span class="keyword">new</span> AsyncTask().execute();</span><br><span class="line"><span class="keyword">new</span> AsyncTask().execute();</span><br></pre></td></tr></table></figure>

<p>那么就会有多个任务了,注意:AsyncTask中的线程池是是<code>static final</code>的,这样就会产生多任务了,那么线程池自然也就派上用场了</p>
<p>(二)在3.0之前的版本,如果提交了多个任务,那么其线程池不是串行执行的,而是并行执行的.</p>
<h2 id="问题-在3-0之后可以依旧使用任务并发执行吗"><a href="#问题-在3-0之后可以依旧使用任务并发执行吗" class="headerlink" title="问题:在3.0之后可以依旧使用任务并发执行吗?"></a>问题:在3.0之后可以依旧使用任务并发执行吗?</h2><p>可以,只不过不要调用<code>new AsyncTask().execute();</code>而是调用<code>new AsyncTask().executeOnExecutor(Executor exec,Params... params)</code>,这时候,我们就可以不使用默认的sDefaultExecutor了,而是我们自己提供一个线程池,实现并发.</p>
<p>我们知道在execute()方法中其实是调用了executeOnExecutor(),而这个方法在3.0之前是没有的,3.0之前直接把execute(),然后线程池就并发执行了,当然了,线程池你也知道,如果你提交的任务数过多,就直接报错的,这也是3.0之前的一个缺点,不可配置.</p>


    </div>









      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    zachaxy
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://zachaxy.github.io/2017/10/17/AsyncTask详解/" title="AsyncTask详解">https://zachaxy.github.io/2017/10/17/AsyncTask详解/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>


    <footer class="post-footer">

        <div class="post-tags">

            <a href="/tags/Android-UI-专题/" rel="tag"># Android UI 专题</a>

        </div>







        <div class="post-nav">
          <div class="post-nav-next post-nav-item">

              <a href="/2017/06/05/Objective-C快速上手/" rel="next" title="Objective-C快速上手">
                <i class="fa fa-chevron-left"></i> Objective-C快速上手
              </a>

          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">

              <a href="/2017/10/20/Maven简介/" rel="prev" title="Maven简介">
                Maven简介 <i class="fa fa-chevron-right"></i>
              </a>

          </div>
        </div>




    </footer>
  </div>



  </article>



    <div class="post-spread">

    </div>
  </div>


          </div>









        </div>



  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">

      <div id="sidebar-dimmer"></div>

    <div class="sidebar-inner">




        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>


      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">

              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="zachaxy">

              <p class="site-author-name" itemprop="name">zachaxy</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">


              <div class="site-state-item site-state-posts">

                <a href="/archives">

                  <span class="site-state-item-count">64</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>







              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>


          </nav>



          <div class="links-of-author motion-element">


                <span class="links-of-author-item">
                  <a href="https://github.com/zachaxy" target="_blank" title="GitHub">

                      <i class="fa fa-fw fa-globe"></i>GitHub</a>
                </span>

                <span class="links-of-author-item">
                  <a href="https://weibo.com/3242765540" target="_blank" title="Weibo">

                      <i class="fa fa-fw fa-globe"></i>Weibo</a>
                </span>


          </div>









        </div>
      </section>


      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">






              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#AsyncTask详解"><span class="nav-number">1.</span> <span class="nav-text">AsyncTask详解</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#AsyncTask中的参数"><span class="nav-number">1.1.</span> <span class="nav-text">AsyncTask中的参数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AsyncTask中一些重要的方法"><span class="nav-number">1.2.</span> <span class="nav-text">AsyncTask中一些重要的方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AsyncTask的基本使用"><span class="nav-number">1.3.</span> <span class="nav-text">AsyncTask的基本使用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AsyncTask中的注意事项"><span class="nav-number">1.4.</span> <span class="nav-text">AsyncTask中的注意事项</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AsyncTask源码解析"><span class="nav-number">1.5.</span> <span class="nav-text">AsyncTask源码解析</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#问题-既然AsyncTask只能execute一次-要线程池干什么"><span class="nav-number">2.</span> <span class="nav-text">问题:既然AsyncTask只能execute一次,要线程池干什么?</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#问题-在3-0之后可以依旧使用任务并发执行吗"><span class="nav-number">3.</span> <span class="nav-text">问题:在3.0之后可以依旧使用任务并发执行吗?</span></a></li></ol></div>


          </div>
        </section>
      <!--/noindex-->




    </div>
  </aside>



      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zachaxy</span>


    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>

      <span class="post-meta-item-text">站点文章字数总计&#58;</span>

    <span title="站点文章字数总计">147.9k</span>

</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>













      </div>
    </footer>


      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>

          <span id="scrollpercent"><span>0</span>%</span>

      </div>




  </div>



<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
























    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>




    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>




    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>






  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>







  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>






  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>







































  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>

















  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>





</body>
</html>
